package io.renren.modules.bike.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import io.renren.common.utils.DateUtil;
import io.renren.modules.app.service.UserService;
import io.renren.modules.bike.entity.BikeEntity;
import io.renren.modules.bike.entity.MoneyEntity;
import io.renren.modules.bike.service.BikeService;
import io.renren.modules.bike.service.MoneyService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.renren.modules.bike.entity.OrdersEntity;
import io.renren.modules.bike.service.OrdersService;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;

import static io.renren.common.utils.ShiroUtils.getUserId;


/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2022-03-14 10:48:53
 */
@RestController
@RequestMapping("bike/orders")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("bike:orders:list")
    public R list(@RequestParam Map<String, Object> params) {
        Long userId = getUserId();
        if (userId == 10) {
            PageUtils page = ordersService.queryPageWeiXiu(params);
            return R.ok().put("page", page);
        } else if (userId == 1) {
            PageUtils page = ordersService.queryPage(params);
            return R.ok().put("page", page);
        } else {
            PageUtils page = ordersService.queryPageUser(params);

            return R.ok().put("page", page);
        }

    }


    /**
     * 信息
     */
    @RequestMapping("/info/{oid}")
    @RequiresPermissions("bike:orders:info")
    public R info(@PathVariable("oid") Integer oid) {
        OrdersEntity orders = ordersService.getById(oid);

        return R.ok().put("orders", orders);
    }

    @Autowired
    BikeService bikeService;

    @Autowired
    MoneyService moneyService;

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("bike:orders:save")
    public R save(@RequestBody OrdersEntity orders) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        Long userId = getUserId();
        if (userId != 1 && userId != 10) {
            MoneyEntity moneyEntity = moneyService.selectOne(getUserId());
           if (moneyEntity==null){
               return R.error("余额不足，请先充值！");
           }
            if (Float.parseFloat(moneyEntity.getMoney()) < 10) {
                return R.error("余额不足10元，请先充值！");
            }
            BikeEntity bikeEntity = bikeService.getById(orders.getOBid());
            String bState = bikeEntity.getBState();
            if (bState.equals("未借") || bState.equals("已归还")) {
                orders.setOCreateTime(date);
                orders.setOBorrowTime(date);
                orders.setOSno(String.valueOf(userId));
                bikeEntity.setBState("未归还");
                bikeService.updateById(bikeEntity);
                orders.setOState("未归还");
                ordersService.save(orders);
                return R.ok("租赁成功，请注意安全！");
            } else {
                return R.error("当前单车不可用，请选择其他车辆");
            }
        } else {
            ordersService.save(orders);
            return R.ok();
        }
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("bike:orders:update")
    public R update(@RequestBody OrdersEntity orders) throws ParseException {
        Long userId = getUserId();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(new Date());
        if (userId != 1 && userId != 10) {
            //设置订单归还时间
            orders.setOReturnTime(date);
            orders.setOUpdateTime(date);

            // 这里设置结算的费用(起止时间*2=money)
            // 开始时间
            Date beginTime = DateUtil.yMdHmsToDate(orders.getOBorrowTime());
            double ceil = Math.ceil(DateUtil.differHour(beginTime, new Date()));

            // 归还时间
            Date returnTime = DateUtil.yMdHmsToDate(orders.getOReturnTime());
            double ceil1 = Math.ceil(DateUtil.differHour(returnTime, new Date()));

            float beginEnd = (float) (ceil - ceil1);
            orders.setOMoney((beginEnd * 2));
            MoneyEntity entity = moneyService.selectOne(userId);
            String money = entity.getMoney();
            if (Float.parseFloat(money) - beginEnd * 2 < 0) {
                return R.error("余额不足，请充值后再操作！");
            }
            String realMoney = String.valueOf(Float.parseFloat(entity.getMoney()) - beginEnd * 2);
            entity.setMoney(realMoney);
            moneyService.updateById(entity);

            bikeService.updateByOBid(orders.getOBid());
            orders.setOState("已归还");
            boolean update = ordersService.updateById(orders);
            if (update) {
                return R.ok("归还成功，感谢使用！");
            } else {
                return R.error("归还失败，请稍后再试...");
            }
        }
        ordersService.updateById(orders);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("bike:orders:delete")
    public R delete(@RequestBody Integer[] oids) {
        ordersService.removeByIds(Arrays.asList(oids));

        return R.ok();
    }

}
